import Two from "two.js";
import { IAnimationConfig } from "@/plugins/store";
import * as loash from "lodash-es";

// 图形显示的类型
export interface IObject {
  /**
   * 初始化自身的一些参数, 将形状画出来
   * @param two
   * @constructor
   */
  init(two: Two, cfg?: IAnimationConfig): void;

  /**
   * 执行下一帧操作
   * @param frame
   * @param speed
   * @constructor
   */
  next(frame: number, speed?: number): void;
}

/**
 * 动画执行类
 * 使用的顺序:
 * new
 * addObject
 * run
 */
export class Animation {
  private readonly two: Two;
  private cfg: IAnimationConfig;

  private objects: Array<IObject> = [];

  constructor(cfg: IAnimationConfig) {
    this.two = new Two({ fullscreen: true });

    this.two.bind("update", (frame: number) => {
      // console.log(frame);
      this.onUpdate(frame);
    });
    this.cfg = cfg;

    // 根据宽度 x y 要进行缩比
    // 最远距离的点 + 20
    this.cfg.scale = <number>(
      loash.min([
        this.two.width / this.cfg.xMax,
        this.two.height / this.cfg.yMax,
      ])
    );
  }

  public addObject(object: IObject) {
    this.objects.push(object);
  }

  private onUpdate(frame: number) {
    // console.log(`[Animation] 当前帧:`, frame);
    this.objects.forEach((value) => {
      value.next(frame, this.cfg.speed);
    });
  }

  private initObjects() {
    this.objects.forEach((value) => {
      value.init(this.two, this.cfg);
    });
  }

  public run(el = document.body) {
    this.initObjects();
    this.two.appendTo(el).play();

    setTimeout(() => this.pause(), this.cfg.time * 1000);
  }

  public clear() {
    this.two.pause();
    this.two.clear();
  }

  public pause() {
    this.two.pause();
  }
}
